﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Rocket.Core.Common;
using System.Reflection;
using Rocket.Core;

namespace Rocket.Windows.Framework.Utilities
{
    public partial class DataGridViewPlus<V> : DataGridView
         where V : BaseObject 
    {
        public DataGridViewPlus()
        {
        }

        protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e)
        {
            base.OnDataBindingComplete(e);

            Type t = typeof(V);
            // get all relevant properties           
            foreach (PropertyInfo p in t.GetProperties(BindingFlags.Instance |
                BindingFlags.Public |
                BindingFlags.FlattenHierarchy))
            {
                DataGridViewColumn col = this.Columns[p.Name];
                
                if (col != null)
                {
                    col.ReadOnly = true;
                    // get all custom attributes of type ShowInGridAttribute    
                    object[] attributesEnable = p.GetCustomAttributes(typeof(EnableCellEditAttribute),
                        false);
                    if (attributesEnable.Length == 1)
                    {    
                        // we have 1 attribute, check to see if we want to show it and which text to use          
                        EnableCellEditAttribute a = (EnableCellEditAttribute)attributesEnable[0];
                        if (a.CellEditable)
                        {
                            this.ReadOnly = false;
                            col.ReadOnly = false;
                        }      
                    }

                    object[] attributes = p.GetCustomAttributes(typeof(ShowInGridAttribute), false);
                    if (attributes.Length == 1)
                    {
                        // we have 1 attribute, check to see if we want to show it and which text to use          
                        ShowInGridAttribute a = (ShowInGridAttribute)attributes[0];
                        string colText = a.ColumnText != String.Empty ? a.ColumnText : col.HeaderText;
                        col.Visible = a.ColumnVisible;
                        col.HeaderText = colText;
                    }
                }
            }
        }

    }
}
